import axios from 'axios';
import { LoginForm, RegisterForm, LoginResponse, Todo } from '../types';

const baseURL = 'http://113.45.152.122:3001/api';

const api = axios.create({
  baseURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  }
});

// 请求拦截器
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 响应拦截器
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error.response?.data || error);
  }
);

export const authAPI = {
  login: async (data: LoginForm): Promise<LoginResponse> => {
    try {
      const response = await api.post('/auth/login', data);
      return response.data;
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  },
  register: (data: RegisterForm) => api.post('/users', data),
};

export const todoAPI = {
  getList: () => api.get<Todo[]>('/tasks'),
  getById: (id: number) => api.get<Todo>(`/tasks/${id}`),
  create: (data: Partial<Todo>) => api.post('/tasks', {
    title: data.title,
    description: data.content,
    completed: data.status === 1,
    categoryId: data.category,
    tagIds: data.tags
  }),
  update: (id: number, data: Partial<Todo>) => api.patch(`/tasks/${id}`, {
    title: data.title,
    description: data.content,
    completed: data.status === 1,
    categoryId: data.category,
    tagIds: data.tags
  }),
  delete: (id: number) => api.delete(`/tasks/${id}`),
};

export const categoryAPI = {
  getList: () => api.get('/categories'),
  create: (data: { name: string; color?: string }) => api.post('/categories', data),
  update: (id: number, data: { name?: string; color?: string }) => 
    api.patch(`/categories/${id}`, data),
  delete: (id: number) => api.delete(`/categories/${id}`),
};

export const tagAPI = {
  getList: () => api.get('/tags'),
  create: (data: { name: string; color?: string }) => api.post('/tags', data),
  update: (id: number, data: { name?: string; color?: string }) => 
    api.patch(`/tags/${id}`, data),
  delete: (id: number) => api.delete(`/tags/${id}`),
};

export const statisticsAPI = {
  getCompletionTrend: (days?: number) => 
    api.get('/statistics/completion-trend', { params: { days } }),
  getCategoryDistribution: () => 
    api.get('/statistics/category-distribution'),
  getSummary: () => 
    api.get('/statistics/summary'),
};

export default api;